package durak.server.control;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import durak.server.model.Player.playerType;

/**
 * Server2ClientsCommunication class is responsible for initializing the
 * communication between the server and the connecting clients - in order to
 * logOn the human players to the game. It holds a reference to game
 */

public class Server2ClientsCommunication {

	private Game gameSession;
	public boolean gameOn;
	ReadFromXmlFile xmlFile;

	public Server2ClientsCommunication(int port, int numHumanPlayers, int autoPlayers, int isXML, String xmlPath) throws Throwable {
		gameSession = new Game(numHumanPlayers, autoPlayers, this);
		gameOn = true;
		int currHumanPlayers = 0;
		if (isXML == 2) {
			xmlFile = new ReadFromXmlFile();
			xmlFile.parseXmlFile(xmlPath);
		}

		if (numHumanPlayers > 0) {
			try {

				System.out.println("Opening port on " + port);
				ServerSocket clientConnectorSocket = new ServerSocket(port);
				System.out.println("Listening for connections");

				initAutoPlayers(autoPlayers, isXML);

				while (gameOn) {

					// block until we get a connection from a client
					final Socket client = clientConnectorSocket.accept();
					System.out.println("Client connected from " + client.getInetAddress());

					PlayerControl player = new PlayerControlHuman(gameSession);
					player.getPlayer().setType(playerType.HUMAN);
					if (isXML == 2) {
						player.getPlayer().setName(xmlFile.returnOnlyHuman().get(currHumanPlayers).getName());
						currHumanPlayers++;
					}
					gameSession.addPlayer(player);
					new Thread(player).start();
					if (gameSession.isGameFull()) {
						while(gameSession.allPlayersReady() == false) {}
						System.out.println("All players are connected. Starting game...");
						gameSession.getCommandHandler().runGame();
					}

				}
			} catch (IOException io) {
				System.out.println("Server Connection Manager Failed...Shutting Down...");
				// if the connection manager fails we want to closedown the
				// server
				System.exit(0);
			}
		} else {
			initAutoPlayers(autoPlayers, isXML);
			System.out.println("All players are connected. Starting game...");
			gameSession.getCommandHandler().runGame();

		}
	}

	/**
	 * @param autoPlayers
	 */
	private void initAutoPlayers(int autoPlayers, int isXML) {
		int currAutoPlayers = 0;
		for (int i = 0; autoPlayers > i; i++) {
			PlayerControl autoPlayer = new PlayerControlAutomatic(gameSession);
			autoPlayer.getPlayer().setType(playerType.COMPUTER);
			if (isXML == 2) {
				autoPlayer.getPlayer().setName(xmlFile.returnOnlyAuto().get(currAutoPlayers).getName());
				currAutoPlayers++;
			}
			autoPlayer.getPlayer().setName("AutoPlayer" + i);
			gameSession.addPlayer(autoPlayer);
		}
	}

}